package com.example.zjsr.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.internal.org.apache.commons.lang3.StringUtils;
import com.example.zjsr.common.CqKey;
import com.example.zjsr.common.Key;
import com.example.zjsr.common.ServerResponse;
import com.example.zjsr.dao.CountDao;
import com.example.zjsr.dao.UserDao;
import com.example.zjsr.domain.*;
import com.example.zjsr.pojo.CqUser;
import com.example.zjsr.pojo.ilabresult.CqSport;
import com.example.zjsr.pojo.ilabresult.Step;
import com.example.zjsr.service.JwtLoginService;
import com.example.zjsr.service.TmpU3dServer;
import com.example.zjsr.service.UserService;
import com.example.zjsr.util.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.catalina.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;


/**
 * 用户模块
 */
@Controller
@RequestMapping("/user")
@CrossOrigin //todo 跨域问题
public class UserController {

    @Autowired
    private TmpU3dServer tmpU3dServer;

    @Autowired
    private UserService userService;

    @Autowired
    private JwtLoginService jwtLoginService;

    @Autowired
    private CountDao countDao;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private CqUtil cqUtil;

    @Autowired
    private FileUploadAndDownload fileUploadAndDownload;

    @Autowired
    private UserDao userDao;

    @Autowired
    private ExcelUtil excelUtil;

    private Logger logger = LoggerFactory.getLogger(UserController.class);


//    @RequestMapping(value = "/updateMD5Password",method = RequestMethod.GET)
//    public ServerResponse<String> updateMD5Password(){
//        return userService.updateMD5Password();
//    }

    /**
     * 前台用户注册接口
     *
     * @param userVo
     * @return
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> register(@RequestBody UserVo userVo, HttpServletRequest request) throws UnsupportedEncodingException {
        /**
         * 接受前台时候出现乱码问题 进行硬编码 todo 2019年8月19日17:38:20 中文参数乱码问题 important
         */
        logger.info("接收到的前台参数为：{}", userVo);
        return userService.register(userVo);
    }

    /**
     * 注册时 1、获取后台生成的邮箱验证码
     * 参数需要安全，接口安全
     *
     * @return
     */
    @RequestMapping(value = "/checkCode", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse<String> sendEmailCode(String email) {
        //根据邮箱获取验证码
        return userService.generateCheckCode(email);
    }


    /**
     * 接入重庆高校 lzb 2022-8-29
     */
    @RequestMapping(value = "/qc/login", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> login(@RequestBody CqUser cqUser, HttpServletRequest request) {
        try {
            request.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.out.println("获取到的重庆高校参数token为：" + cqUser.getToken());
        //获取重庆大学传递过来的token
        String token = cqUser.getToken();
        try {
            String ilabJson = cqUtil.getAccessToken(token);
            JSONObject o = JSONObject.parseObject(ilabJson);
            int code = o.getInteger("code");
            /**
             * 判断code不为0,则从ilab获取内容失败
             */
            if (code != 0) {
                return ServerResponse.createByErrorMsg("token失效，请重新通过重庆高校进入重做实验");
            }
            String data = o.getString("data");
            JSONObject jsonObject = JSONObject.parseObject(data);
            String userNames = jsonObject.getString("userName");
            String accessToken = jsonObject.getString("accessToken");
            String openId = jsonObject.getString("openId");
            String loginName = userNames;
            String username = userNames;
            User user = userService.selectUserByLoginName(loginName);

            if (user != null) {
                user.setRoleId(8);
                user.setLoginName(loginName);
                user.setOpenId(openId);
                user.setAccessToken(URLEncoder.encode(accessToken, "UTF-8"));
                String token1 = JwtUtil.sign(user, 60L * 1000L * 60L * 24);//token有效期24小时
                /**
                 * todo 统计网站访问次数：登陆成功后统计次数变量count加1
                 */
                int num = countDao.selectCount();
                int count = ++num;
                //countDao.updateOne(count);
                redisUtil.del(user.getId()+"module"+1,user.getId()+"module"+2,user.getId()+"module"+3);
                redisUtil.del(user.getId()+"category");//删除水果种类名称
                redisUtil.del(user.getId()+"productParameter");//删除直播参数
                redisUtil.set(user.getId()+"",token,2*3600*5);//将用户的id作为key，token作为value放在redis中
                redisUtil.del(user.getId()+"moduleParameter");//删除场景二U3D传场景三U3D
                redisUtil.del(user.getId()+"analyseData");//删除直播复盘数据
                return ServerResponse.createBySuccess(token1);
            }
            //不存在则在用户数据表中创建用户数据
            UserVo userVo = new UserVo();
            userVo.setLoginName(loginName);
            userVo.setUsername(username);
            userVo.setSchool("重庆高校平台");
            userVo.setProvince("重庆高校平台用户");
            userVo.setCity("重庆高校平台用户");
            //ilab用户身份
            userVo.setRoleId(8);
            userVo.setPassword(MD5.md52("123456"));
            userVo.setEmail("cqgx@163.com");
            int resultCount = userService.insertIlabUser(userVo);
            //插入用户数据 给前端返回user的jwt对象
            User u = userService.selectUserByLoginName(userVo.getLoginName());
            //将access_token放入用户对象生成token
            //u.setRoleId(8);
            //u.setSchool("重庆高校");
            u.setOpenId(openId);
            //u.setLoginName(loginName);
            u.setAccessToken(URLEncoder.encode(accessToken, "UTF-8"));
            System.out.println(URLEncoder.encode(accessToken, "UTF-8"));
            //24小时的token有效期
            String token1 = JwtUtil.sign(u, 60 * 60 * 1000 * 24L);
            int num = countDao.selectCount();
            int count = ++num;
            //countDao.updateOne(count);
            redisUtil.del(u.getId()+"module"+1,u.getId()+"module"+2,u.getId()+"module"+3);
            redisUtil.del(u.getId()+"category");//删除水果种类名称
            redisUtil.del(u.getId()+"productParameter");//删除直播参数
            redisUtil.set(u.getId()+"",token,2*3600*5);//将用户的id作为key，token作为value放在redis中
            redisUtil.del(u.getId()+"moduleParameter");//删除场景二U3D传场景三U3D
            redisUtil.del(u.getId()+"analyseData");//删除直播复盘数据

            return ServerResponse.createBySuccess(token1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ServerResponse.createByErrorMsg("新增重庆高校平台用户失败");
    }

    /**
     * ilab平台用户登陆 2019年10月11日15:50:32
     */
    @RequestMapping(value = "/ilab/login", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> login(@RequestBody String data, HttpServletRequest request, HttpServletResponse response) {
        JSONObject jsonObject = JSON.parseObject(data);
        String jwt = jsonObject.getString("ticket");//jwt<=>ticket
        try {
            logger.info("ilab平台用户进入了{}", jwt);
            // 解析token获取包含username的json字符串
            String appid = String.valueOf(Key.issuerId);
            String AesKey = Key.AesKey;
            String Ticket = URLDecoder.decode(jwt, "UTF-8");
            String SIGNATURE = CipherUtil.generatePassword(Ticket + appid + AesKey);
            //测试地址和正式地址 http://202.205.145.156:8017->http://www.ilab-x.com
            System.out.println("http://http://www.ilab-x.com/open/api/v2/token?ticket=" + jwt + "&appid=" + appid + "&signature=" + SIGNATURE);
            String code = HttpUtil.loadJSON("http://www.ilab-x.com/open/api/v2/token?ticket=" + jwt + "&appid=" + appid + "&signature=" + SIGNATURE);
            // todo ilabJson乱码了！ 2019年10月12日09:39:58
            JSONObject o = JSONObject.parseObject(code);
            logger.info("ilab传过来的ticket解析之后的{}", o);
            Integer codeCheck = o.getInteger("code");
            if (codeCheck != 0) {
                //todo codeCheck是ilab返回的数据信息反馈,案例：({"code":0, "access_token":"4hCwDHmIAf8Bj+TVe7GBVUaLOY0rJiDyWtCmNhixIsBJnZLiAPhmYc0vBLr592Zj","create_time":1598230461000,"create_time_display":"2020-08-24 08:54:21","expires_time":1598237661236,"expires_time_display":"2020-08-24 10:54:21", "un":"username", "dis":"用户姓名"})
                //todo 判断用户ilab返回的ticket是否继续有效(如果不是为0的话，那就是失效；0为ticket有效)
                return ServerResponse.createByACCOUNTError("新增ilab平台用户失败");
            }
            String loginName = o.getString("un");
            String username = loginName;
            //如果数据库存在登陆用户名 则直接返回
            User user = userService.selectUserByLoginName(loginName);
            if (user != null) {
                user.setAccessToken(URLEncoder.encode(o.getString("access_token"), "UTF-8"));
                System.out.println(URLEncoder.encode(o.getString("access_token"), "UTF-8"));
                String token1 = JwtUtil.sign(user, 600L * 1000L * 60L);//token有效期10小时
                Operate operate = new Operate();
                operate.setOperateStyle("ilab用户登录");
                operate.setOperateUser(user.getUsername());
                if (user.getRoleId() == 1) {
                    operate.setOperateRoot("管理员");
                } else if (user.getRoleId() == 2) {
                    operate.setOperateRoot("教师");
                } else if (user.getRoleId() == 3) {
                    operate.setOperateRoot("评审账户");
                } else if (user.getRoleId() == 4) {
                    operate.setOperateRoot("学生");
                }
                operate.setOperateStatus("成功");
                userDao.insertOperate(operate);
                redisUtil.set(user.getId() + "", token1, 2 * 3600 * 5);//将用户的id作为key，token作为value放在redis中
                return ServerResponse.createBySuccess(token1);
            }
            String access_token = o.getString("access_token");
            //todo 不存在则在用户数据表中创建用户数据
            UserVo userVo = new UserVo();
            userVo.setLoginName(loginName);
            userVo.setUsername(username);
            userVo.setSchool("ilab平台用户");
            userVo.setProvince("ilab平台");
            userVo.setCity("ilab平台");
            userVo.setRoleId(4);//学生
            userVo.setPassword("12345");
            userVo.setEmail("ilab@163.com");
            System.out.println("acess_token=" + URLEncoder.encode(access_token, "UTF-8"));
            //必须要把access_token通过encode进行解密（UTF-8）
            int id = userService.ilabInsertUser(userVo);
            userVo.setId(id);
            userVo.setAccessToken(URLEncoder.encode(access_token, "UTF-8"));
            Operate operate = new Operate();
            operate.setOperateStyle("ilab用户登录");
            operate.setOperateUser(userVo.getUsername());
            if (userVo.getRoleId() == 1) {
                operate.setOperateRoot("管理员");
            } else if (userVo.getRoleId() == 2) {
                operate.setOperateRoot("教师");
            } else if (userVo.getRoleId() == 3) {
                operate.setOperateRoot("评审账户");
            } else if (userVo.getRoleId() == 4) {
                operate.setOperateRoot("学生");
            }
            operate.setOperateStatus("成功");
            userDao.insertOperate(operate);
            String token1 = JwtUtil.sign(userVo, 600L * 1000L * 60L);//token1有效期10小时
            redisUtil.set(userVo.getId() + "", token1, 2 * 3600 * 5);//将用户的id作为key，token作为value放在redis中
            return ServerResponse.createBySuccess(token1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ServerResponse.createByACCOUNTError("新增ilab平台用户失败");
    }


    /**
     * 用户登录 成功后给前台返回一个token,后面需要拿这个token去验证
     * todo 用户类型：ilab用户 2019年9月24日15:34:07
     * 前台传入
     *
     * @param userVo
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> login(@RequestBody UserVo userVo) {
        // 如果次数 == 5 那么抛出异常 等待十分钟
        try {
            int usercount = userDao.getUserCount(userVo.getLoginName());
            Date sdbegintime = userDao.getsdbegintime(userVo.getLoginName());
            long timeDifference = ((new Date().getTime() - sdbegintime.getTime()) / 60 / 1000);
            if (usercount >= 5 && timeDifference < 10) {
                return ServerResponse.createByACCOUNTError("错误次数大于五次,账户锁定十分钟");
            }
            if (usercount >= 5 && timeDifference >= 10) {

                userDao.getUserCount2(userVo.getLoginName());
                userDao.gettimepassword(userVo.getLoginName());
            }

        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByACCOUNTError("登陆失败,请重新登录");
        }


        // todo 如果是管理员或者评审专家 直接登陆 admin 123
        logger.info(userVo + "");
        if (userVo.getRoleId() == 1 || userVo.getRoleId() == 3) {
            User user = new User();
            //角色id
            user.setRoleId(userVo.getRoleId());
            //登录名
            user.setLoginName(userVo.getLoginName());
            //登陆密码
            user.setPassword(userVo.getPassword());
            return jwtLoginService.login(user);
        }


//        //验证登陆接口 todo 满足ilab用户验证要求 loginName password nonce cnonce 已解决 2019年9月23日13:11:39
//        String nonce = StringUtil.getRandomString(16);
//        String cnonce = StringUtil.getRandomString(16);
//        String newPassword = SHA256Util.generateShaPwd(nonce,userVo.getPassword(),cnonce);
//        /**
//         * 测试平台url
//         */
//        //String json = HttpUtil.loadJSON("http://202.205.145.156:8017/sys/api/user/validate?username="+userVo.getLoginName()+"&password="+newPassword+"&nonce="+nonce+"&cnonce="+cnonce);
//
//        /**
//         * 正式平台的url ！！！
//         */
//        String json = HttpUtil.loadJSON("http://www.ilab-x.com/sys/api/user/validate?username="+userVo.getLoginName()+"&password="+newPassword+"&nonce="+nonce+"&cnonce="+cnonce);
//        JSONObject object = JSONObject.parseObject(json);
//        int code = object.getInteger("code");
//        // code==0 代表验证成功
//        if(code != 0){
//            //验证不成功 返回错误信息
//            return ServerResponse.createByErrorMsg("请使用ilab平台注册账户！");
//        }
        User user = new User();
        //角色id
        user.setRoleId(userVo.getRoleId());
        //登录名
        user.setLoginName(userVo.getLoginName());
        //登陆密码
        user.setPassword(userVo.getPassword());
        return jwtLoginService.login(user);
    }

    /**
     * 忘记密码时获取验证码 邮箱验证码
     */
    @RequestMapping(value = "/forget_checkCode", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse<String> forgetSendEmailCode(String email) {
        //根据邮箱获取验证码
        return userService.forgetSendEmailCode(email);
    }

    /**
     * 忘记密码时根据邮箱地址获取验证码 更新
     */
    @RequestMapping(value = "/updatePassword", method = RequestMethod.PUT)
    @ResponseBody
    public ServerResponse<String> updatePassword(@RequestBody UserVo userVo) {
        return userService.updatePassword(userVo);
    }


    /**
     * 用户管理 查看所有的数据
     */
    @RequestMapping(value = "/backend/findAll", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<PageInfo<User>> findAll(HttpServletRequest request, @RequestBody String data) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        JSONObject jsonObject = JSON.parseObject(data);
        Integer pageNum = jsonObject.getInteger("pageNum");
        Integer pageSize = jsonObject.getInteger("pageSize");
        if (ObjectUtils.isEmpty(pageNum)) {
            pageNum = 1;
        }
        PageHelper.startPage(pageNum, pageSize);
        List<User> userList = userService.findAll(u);
        PageInfo<User> pageInfo = new PageInfo<User>(userList);
        return ServerResponse.createBySuccess(pageInfo);
    }

    /**
     * 新增后台用户管理记录
     */
    @RequestMapping(value = "/backend/add", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> addUser(@RequestBody UserVo userVo, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        int j = userDao.getOnlyLoginname(userVo.getLoginName());
        if (j > 0) {
            return ServerResponse.createByErrorMsg("登录名称已经存在");
        }


        int i = userDao.getOnlyOne(userVo.getEmail());
        if (i > 0) {
            return ServerResponse.createByErrorMsg("该邮箱已经存在");

        }
        return userService.insertBackUser(userVo);
    }


    /**
     * 获取用户操作信息
     */
    @RequestMapping(value = "/getOperateInfo", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse getOperateInfo(HttpServletRequest request, @RequestBody String data) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        JSONObject jsonObject = JSON.parseObject(data);
        Integer pageNum = jsonObject.getInteger("pageNum");
        Integer pageSize = jsonObject.getInteger("pageSize");
        return userService.getOperateInfo(pageNum, pageSize);
    }

    /**
     * 下载操作日志
     *
     * @param response
     */
    @RequestMapping(value = "/downLoadOperateInfo", method = RequestMethod.GET)
    @ResponseBody
    public void downLoadOperateInfo(HttpServletResponse response) {
        ServletOutputStream out = null;
        List<DownOperate> downOperateList = userService.downLoadOperateInfo();
        try {
            out = response.getOutputStream();
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            String fileName = "操作日志记录";
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");
            ExcelUtils.writeExcel(out, DownOperate.class, downOperateList);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * u3d刷新页面缓存删除
     */
    @RequestMapping(value = "/reFresh", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> reFresh(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        //删除临时表一条记录
        Integer id = u.getId();
        userService.deleteByUserId2(id);
        redisUtil.del(u.getId() + "module" + 1, u.getId() + "module" + 2, u.getId() + "module" + 3);
        redisUtil.del(u.getId() + "category");//删除水果种类名称
        redisUtil.del(u.getId() + "productParameter");//删除直播参数
        redisUtil.del(u.getId() + "moduleParameter");//删除场景二U3D传场景三U3D
        redisUtil.del(u.getId() + "analyseData");//删除直播复盘数据
        return ServerResponse.createBySuccessMsg("刷新成功");
    }

    /**
     * 根据用户id删除User表数据
     */

    @RequestMapping(value = "/deleteByUserId", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> deleteById(HttpServletRequest request, @RequestBody String data) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        JSONObject jsonObject = JSON.parseObject(data);
        Integer id = jsonObject.getInteger("id");
        return userService.deleteByUserId(id);
    }

    /**
     * 修改用户信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/backend/update", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> updateBackendUser(@RequestBody User user, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/

        int i = userDao.getOnlyOne2(user.getEmail(), user.getId());
        if (i > 0) {
            return ServerResponse.createByErrorMsg("该邮箱已经存在");

        }

        int j = userDao.getOnlyLoginname2(user.getLoginName(), user.getId());
        if (j > 0) {
            return ServerResponse.createByErrorMsg("登录名称已经存在");
        }
        String password = user.getPassword();

        user.setPassword(MD5.md52(password));
        return userService.updateBackendUser(user);
    }

    /**
     * 根据用户id查询用户信息
     */

    @RequestMapping(value = "/backend/findById", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<User> findUserById(HttpServletRequest request, @RequestBody String data) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        JSONObject jsonObject = JSON.parseObject(data);
        Integer id = jsonObject.getInteger("id");
        return userService.findById(id);
    }

    /**
     * 用户查询功能(学校、姓名、登录名查询)
     */
    @RequestMapping(value = "/backend/findByParams", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<PageInfo<User>> findByParams(HttpServletRequest request, @RequestBody String data) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        JSONObject jsonObject = JSON.parseObject(data);
        Integer pageNum = jsonObject.getInteger("pageNum");
        Integer pageSize = jsonObject.getInteger("pageSize");
        String school = jsonObject.getString("school");
        String username = jsonObject.getString("username");
        String loginName = jsonObject.getString("loginName");
        String classes = jsonObject.getString("classes");
        PageHelper.startPage(pageNum, pageSize);
        User user = new User();
        user.setUsername(username);
        user.setSchool(school);
        user.setLoginName(loginName);
        user.setClasses(classes);
        List<User> userList = userService.findByParams(user);
        PageInfo<User> pageInfo = new PageInfo<User>(userList);
        return ServerResponse.createBySuccess(pageInfo);
    }

    /**
     * 统计功能：统计用户总数量
     */
    @GetMapping("/userAccount")
    @ResponseBody
    public ServerResponse<Integer> userAccount(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if (!jwt.equals(redisUtil.get(u.getId() + ""))) {
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        return userService.accountUser();
    }


    /**
     * 获取水果信息字段
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getFruitField", method = RequestMethod.GET)
    public ServerResponse getFruitField(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        return userService.getFruitField();
    }


    /**
     * 游客登录（一个游客一个账号）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "expertLogin", method = RequestMethod.POST)
    public ServerResponse<String> expertLogin() {
        User expertLoginUser = new User();
        expertLoginUser.setRoleId(3);
        expertLoginUser.setUsername("评审账户");
        expertLoginUser.setLoginName("pszh" + System.currentTimeMillis());
        expertLoginUser.setPassword("mima" + System.currentTimeMillis());
        expertLoginUser.setSchool("浙江树人大学");
        expertLoginUser.setProvince("浙江省");
        expertLoginUser.setCity("杭州市");
        userService.expertLogin(expertLoginUser);
        String token = JwtUtil.sign(expertLoginUser, 60L * 2000L * 60L);//token有效期10小时
        redisUtil.set(expertLoginUser.getId() + "", token);//将用户的id作为key，token作为value放在redis中
        logger.info("用户信息" + expertLoginUser, 2 * 3600);
        return ServerResponse.createBySuccess(token);
    }


    /**
     * 用户添加直播平台信息
     *
     * @param request
     * @param file
     * @param livePlatform
     * @param textContent
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/addPlatform")
    public ServerResponse addPlatform(HttpServletRequest request, MultipartFile file, String livePlatform, String textContent) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        Platform platform = new Platform();
        try {
            String icon = fileUploadAndDownload.upload(file);
            if (StringUtils.isEmpty(icon)) {
                return ServerResponse.createByACCOUNTError("上传图标失败！");
            } else {
                platform.setIcon(icon);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByACCOUNTError("上传图标失败！");
        }
        platform.setLivePlatform(livePlatform);
        platform.setTextContent(textContent);
        return userService.addPlatform(platform);
    }


    /**
     * 根据直播平台编号来删除某个直播平台信息
     *
     * @param request
     * @param data
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/deletePlatform")
    public ServerResponse deletePlatform(HttpServletRequest request, @RequestBody String data) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        JSONObject jsonObject = JSON.parseObject(data);
        Integer platformId = jsonObject.getInteger("platformId");
        return userService.deletePlatform(platformId);
    }


    /**
     * 修改直播平台信息
     *
     * @param request
     * @param file
     * @param platform
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/updatePlatform")
    public ServerResponse updatePlatform(HttpServletRequest request, MultipartFile file, Platform platform) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        if (null != file) {
            try {
                String icon = fileUploadAndDownload.upload(file);
                if (StringUtils.isEmpty(icon)) {
                    return ServerResponse.createByACCOUNTError("上传图标失败！");
                } else {
                    platform.setIcon(icon);
                }
            } catch (Exception e) {
                e.printStackTrace();
                return ServerResponse.createByACCOUNTError("上传图标失败！");
            }
        }
        return userService.updatePlatform(platform);
    }

    /**
     * 获取直播信息
     *
     * @param request
     * @param data（platformId 直播平台编号）
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/getPlatform")
    public ServerResponse getPlatform(HttpServletRequest request, @RequestBody String data) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        JSONObject jsonObject = JSON.parseObject(data);
        Integer platformId = jsonObject.getInteger("platformId");
        return userService.getPlatform(platformId);
    }


    /**
     * 添加题目大标题（例如仪容仪表）
     *
     * @param request（题目大标题名称，编号自增）
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/addHeadline")
    public ServerResponse addHeadline(HttpServletRequest request, @RequestBody String data) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        JSONObject jsonObject = JSON.parseObject(data);
        String headlineTitle = jsonObject.getString("headlineTitle");
        return userService.addHeadline(headlineTitle);
    }


    /**
     * 删除题目大标题
     *
     * @param request
     * @param data（大标题编号）
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/deleteHeadline")
    public ServerResponse deleteHeadline(HttpServletRequest request, @RequestBody String data) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        JSONObject jsonObject = JSON.parseObject(data);
        Integer headlineId = jsonObject.getInteger("headlineId");
        return userService.deleteHeadline(headlineId);
    }


    /**
     * 获取到所有的题目大标题
     *
     * @param request
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/getHeadline")
    public ServerResponse getHeadline(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        return userService.getHeadline();
    }


    /**
     * 修改题目大标题
     *
     * @param request
     * @param headline
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/updateHeadline")
    public ServerResponse updateHeadline(HttpServletRequest request, @RequestBody Headline headline) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        return userService.updateHeadline(headline);
    }


    /**
     * 添加仪容仪表题目描述
     *
     * @param request
     * @param file【】文件、choose 是否是第几个正确答案、answerIds 是否需要修改的答案编号字符串，用逗号去隔开
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addTopic")
    public ServerResponse addTopic(HttpServletRequest request, Integer headlineId, String topicTitle, String analysis, MultipartFile file[], Integer choose) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        Topic topic = new Topic();
        topic.setTopicTitle(topicTitle);
        topic.setAnalysis(analysis);
        topic.setHeadlineId(headlineId);
        String[] path = new String[file.length];
        try {
            for (int i = 0; i < file.length; i++) {
                path[i] = fileUploadAndDownload.upload(file[i]);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByACCOUNTError("上传答案图片失败");
        }
        List<Answer> answerList = new ArrayList<>();
        for (int i = 0; i < path.length; i++) {
            Answer answer = new Answer();
            answer.setPath(path[i]);
            if (i == choose) {
                answer.setStatus(true);
            } else {
                answer.setStatus(false);
            }
            answerList.add(answer);
        }
        topic.setAnswerList(answerList);
        return userService.addTopic(topic);
    }

    /**
     * 修改仪容仪表题目描述
     *
     * @param request
     * @param topic   参数、file文件、choose 是否是第几个正确答案、answerIds 是否需要修改的答案编号字符串，用逗号去隔开
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateTopic")
    public ServerResponse updateTopic(HttpServletRequest request, Topic topic, MultipartFile file[], Integer choose, String answerIds) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/

        List<Answer> answerList = new ArrayList<>();

        if (StringUtils.isEmpty(answerIds)) {
            return userService.updateTopic(topic, choose);
        }
        String[] path = new String[file.length];
        try {
            for (int i = 0; i < file.length; i++) {
                path[i] = fileUploadAndDownload.upload(file[i]);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByACCOUNTError("上传答案图片失败");
        }
        String[] answers = answerIds.split(",");
        int[] answerId = new int[answers.length];
        for (int i = 0; i < answers.length; i++) {
            answerId[i] = Integer.parseInt(answers[i]);
        }
        for (int i = 0; i < answerId.length; i++) {
            Answer answer = new Answer();
            answer.setAnswerId(answerId[i]);
            if (path.length != 0) {
                answer.setPath(path[i]);
            }
            answerList.add(answer);
        }
        topic.setAnswerList(answerList);
        return userService.updateTopic(topic, choose);
    }


    /**
     * 根据仪容仪表主标题来获取题目
     *
     * @param request
     * @param data
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getTopic")
    public ServerResponse getTopic(HttpServletRequest request, @RequestBody String data) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        JSONObject jsonObject = JSON.parseObject(data);
        Integer headlineId = jsonObject.getInteger("headlineId");
        return userService.getTopic(headlineId);
    }

    /**
     * 删除题目
     *
     * @param request
     * @param data
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/deleteTopic")
    public ServerResponse deleteTopic(HttpServletRequest request, @RequestBody String data) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        JSONObject jsonObject = JSON.parseObject(data);
        Integer topicId = jsonObject.getInteger("topicId");
        return userService.deleteTopic(topicId);
    }


    /**
     * 添加答案图片、答案解析
     *
     * @param request
     * @param file
     * @param topicId
     * @param choose
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addAnswer")
    public ServerResponse addAnswer(HttpServletRequest request, MultipartFile file[], Integer topicId, Integer choose) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        String[] path = new String[file.length];
        try {
            for (int i = 0; i < file.length; i++) {
                path[i] = fileUploadAndDownload.upload(file[i]);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByACCOUNTError("上传答案图片失败");
        }
        List<Answer> answerList = new ArrayList<>();
        for (int i = 0; i < path.length; i++) {
            Answer answer = new Answer();
            answer.setPath(path[i]);
            answer.setTopicId(topicId);
            if (i == choose) {
                answer.setStatus(true);
            } else {
                answer.setStatus(false);
            }
            answerList.add(answer);
        }
        return userService.addAnswer(answerList);
    }


    /**
     * 修改答案图片状态（暂时先不用）
     *
     * @param request
     * @param answerId
     * @param file
     * @param status
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateAnswer")
    public ServerResponse updateAnswer(HttpServletRequest request, Integer answerId, MultipartFile file, boolean status) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        Answer answer = new Answer();
        if (null != file) {
            String path = fileUploadAndDownload.upload(file);
            answer.setPath(path);
        }
        answer.setStatus(status);
        answer.setAnswerId(answerId);
        return userService.updateAnswer(answer);
    }


    /**
     * 根据题目编号 来获取答案信息
     *
     * @param request
     * @param data
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getAnswer")
    public ServerResponse getAnswer(HttpServletRequest request, @RequestBody String data) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        JSONObject jsonObject = JSON.parseObject(data);
        Integer topicId = jsonObject.getInteger("topicId");
        return userService.getAnswer(topicId);
    }


    /**
     * 获取成绩
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getScore", method = RequestMethod.POST)
    public ServerResponse getScore(HttpServletRequest request, @RequestBody String data) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        JSONObject jsonObject = JSON.parseObject(data);
        Integer pageNum = jsonObject.getInteger("pageNum");
        Integer pageSize = jsonObject.getInteger("pageSize");
        return userService.getScore(pageNum, pageSize, u);
    }


    /**
     * 添加分数情况
     *
     * @param request
     * @param score
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addScore", method = RequestMethod.POST)
    public ServerResponse addScore(HttpServletRequest request, @RequestBody Score score) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if (!jwt.equals(redisUtil.get(u.getId() + ""))) {
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/

        if (u.getRoleId().equals(8)) {
            CqSport cqSport = score.getCqSport();
            cqSport.setOriginId(UUID.randomUUID().toString().replaceAll("[a-zA-Z]", "").replaceAll("-", ""));
            cqSport.setOpenId(u.getOpenId());
            cqSport.setStatus(1);
            cqSport.setScore(100);
            cqSport.setStartTime(1654070658955L);
            cqSport.setEndTime(1654074258955L);
            cqSport.setTimeUsed(3600);
            cqSport.setAppId(CqKey.issuerId);
            cqSport.setTitle("跨境电商直播");
            cqSport.setAccessToken(u.getAccessToken());
            cqSport.getSteps().forEach(
                    step -> {
                        step.setEvaluation("百分制");
                        if (step.getTitle().equals("实验简介") || step.getTitle().equals("安全教育")) {
                            step.setScoringModel("时长+测试");
                        } else {
                            step.setScoringModel("操作+测试");
                        }
                    }
            );
            //提交成绩
            String response = cqUtil.submitGrade(cqSport, u.getAccessToken());
            System.out.println(response);
            JSONObject jsonObject = JSONObject.parseObject(response);
            System.out.println(jsonObject);
            if (jsonObject.getInteger("code") != 0) {
                return ServerResponse.createByErrorMsg("上传ilab实验成绩失败");
            }
        }
        //将 userid 对应的 cq_tmp 一条 删除
        tmpU3dServer.delectTmpU3d(u.getId());
        return userService.addScore(score, u);
    }

    /**
    * @Author: liuzhaobo
    * @Description: 步骤
    *   1  判断用户登录角色
    *   2  如果是重庆高校登录 先发重庆高校  iable理论上适用
    *   3  保存本地一份
    * @DateTime: 2022/9/29 0029 9:10
    * @Params:
    * @Return
    */
    @ResponseBody
    @RequestMapping(value = "/addScoreQc", method = RequestMethod.POST)
    public ServerResponse addScoreQc(HttpServletRequest request, @RequestBody ScoreQc scoreQc) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        if(u.getRoleId() == 8){
            CqSport cqSport = scoreQc.getCqSport();
            cqSport.setOriginId(UUID.randomUUID().toString().replaceAll("[a-zA-Z]", "").replaceAll("-", ""));
            cqSport.setOpenId(u.getOpenId());
            cqSport.setStatus(1);
            cqSport.setAppId(CqKey.issuerId);
            cqSport.setAccessToken(u.getAccessToken());
            cqSport.setTitle("电商直播虚拟仿真");
/*            cqSport.setStartTime(1654070658955L);
            cqSport.setEndTime(1654071658995L);*/
            //提交成绩
            String response = cqUtil.submitGrade(cqSport, u.getAccessToken());
            System.out.println(response);
            JSONObject jsonObject = JSONObject.parseObject(response);
            System.out.println(jsonObject);

            if (jsonObject.getInteger("code") != 0) {
                return ServerResponse.createByErrorMsg("上传重庆高校失败");
            }else {
                System.out.println("上传重庆高校成功");
            }

        }
        //将 userid 对应的 cq_tmp 一条 删除
        tmpU3dServer.delectTmpU3d(u.getId());
        scoreQc.setUserId(u.getId());
        CqSport cqSport = scoreQc.getCqSport();
        List<Step> steps = cqSport.getSteps();
        scoreQc.setStep(String.valueOf(steps));
        int i = userService.addScoreBd(scoreQc);
        if(i == 1){
            return ServerResponse.createBySuccess();
        }else {
            return ServerResponse.createByError();
        }

    }


    /**
     * 根据成绩编号来获取详细信息
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getScoreById", method = RequestMethod.POST)
    public ServerResponse getScoreById(HttpServletRequest request, @RequestBody String data) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        JSONObject jsonObject = JSON.parseObject(data);
        Integer scoreId = jsonObject.getInteger("scoreId");
        return userService.getScoreById(scoreId);
    }


    /**
     * 通过编号删除成绩
     *
     * @param request
     * @param data
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/deleteScoreById", method = RequestMethod.POST)
    public ServerResponse deleteScoreById(HttpServletRequest request, @RequestBody String data) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        JSONObject jsonObject = JSON.parseObject(data);
        Integer scoreId = jsonObject.getInteger("scoreId");
        return userService.deleteScoreById(scoreId);
    }


    /**
     * 批改成绩
     *
     * @param request
     * @param data
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/readScoreById", method = RequestMethod.POST)
    public ServerResponse readScoreById(HttpServletRequest request, @RequestBody String data) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        JSONObject jsonObject = JSON.parseObject(data);
        Integer scoreId = jsonObject.getInteger("scoreId");
        String teacherComment = jsonObject.getString("teacherComment");
        return userService.readScoreById(scoreId, teacherComment);
    }


    /**
     * 获取题目类型、题目、答案
     *
     * @param request
     * @param data
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getAllAnswer")
    public ServerResponse getAllAnswer(HttpServletRequest request, @RequestBody String data) {
//        String token = request.getHeader("Authorization");
//        String jwt = token.substring(token.lastIndexOf(" ")+1);
//        User u = JwtUtil.unsign(jwt,User.class);
//        if(u == null){
//            return ServerResponse.createByErrorMsg("token无效");
//        }
//        if(!jwt.equals(redisUtil.get(u.getId()+""))){
//            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
//        }
        JSONObject jsonObject = JSON.parseObject(data);
        Integer headlineId = jsonObject.getInteger("headlineId");
        return userService.getAllAnswer(headlineId);
    }


    /**
     * 删除答案（根据答案信息）
     *
     * @param request
     * @param data
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/deleteAnswers")
    public ServerResponse deleteAnswers(HttpServletRequest request, @RequestBody String data) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        JSONObject jsonObject = JSON.parseObject(data);
        Integer answerId = jsonObject.getInteger("answerId");
        return userService.deleteAnswers(answerId);
    }


    /**
     * 获取u3d提交直播中数据复盘数据（前端制作图表）
     *
     * @param request
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/getAnalyseData")
    public ServerResponse getAnalyseData(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        try {
            AnalyseChart analyseChart = null;//规整好的图表
            analyseChart = new AnalyseChart();
            AnalyseData analyseData = (AnalyseData) redisUtil.get(u.getId() + "analyseData");
            ProductParameter productParameter = (ProductParameter) redisUtil.get(u.getId() + "productParameter");
            analyseChart.setInventory(productParameter.getInventory());
            analyseChart.setFansIncreaseNumber(analyseData.getFansIncreaseNumber());
            analyseChart.setFansNumber(analyseData.getFansNumber());
            analyseChart.setSalesVolume(analyseData.getSalesVolume());
            analyseChart.setViewsNumber(analyseData.getViewsNumber());
            List<AnalyseDetail> analyseDetailList = analyseData.getAnalyseDetailList();
            String[] salesX = analyseDetailList.get(0).getDataX().split(",");//销售额图表X轴数据
            analyseChart.setSalesX(salesX);
            String[] salesY = analyseDetailList.get(0).getDataY().split(",");//销售额图表Y轴数据
            analyseChart.setSalesY(salesY);
            String[] salesVolumeX = analyseDetailList.get(1).getDataX().split(",");//销量图表X轴数据
            analyseChart.setSalesVolumeX(salesVolumeX);
            String[] salesVolumeY = analyseDetailList.get(1).getDataY().split(",");//销量图表Y轴数据
            analyseChart.setSalesVolumeY(salesVolumeY);
            String[] fansNumberChangeX = analyseDetailList.get(2).getDataX().split(",");//粉丝数量变化图表X轴数据
            analyseChart.setFansNumberChangeX(fansNumberChangeX);
            String[] fansNumberChangeY = analyseDetailList.get(2).getDataY().split(",");//粉丝数量变化图表Y轴数据
            analyseChart.setFansNumberChangeY(fansNumberChangeY);
            String[] activeX = analyseDetailList.get(3).getDataX().split(",");//活跃值图表X轴数据
            analyseChart.setActiveX(activeX);
            String[] activeY = analyseDetailList.get(3).getDataY().split(",");//活跃值图表Y轴数据
            analyseChart.setActiveY(activeY);
            String[] evaluationX = analyseDetailList.get(4).getDataX().split(",");//评价图表X轴数据
            analyseChart.setEvaluationX(evaluationX);
            String[] evaluationY = analyseDetailList.get(4).getDataY().split(",");//评价图表Y轴数据
            analyseChart.setEvaluationY(evaluationY);
            String[] favorableRatingX = analyseDetailList.get(5).getDataX().split(",");//好评率图表X轴数据
            analyseChart.setFavorableRatingX(favorableRatingX);
            String[] favorableRatingY = analyseDetailList.get(5).getDataY().split(",");//好评率图表Y轴数据
            analyseChart.setFavorableRatingY(favorableRatingY);
            return ServerResponse.createBySuccess(analyseChart);
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByACCOUNTError("查询失败");
        }

    }


    /**
     * 统计总的实验次数
     */
    @PostMapping("/expAcct")
    @ResponseBody
    public ServerResponse<Integer> experimentAccount(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        return userService.accountExp();
    }

    /**
     * 统计总的实验时间，单位是秒s
     */
    @RequestMapping(value = "/expTime", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<Integer> totalExpCount(HttpServletRequest request) {
//        System.out.println("这个方法可以跨域访问/////");
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        return userService.countTotalExpTime();
    }

    @GetMapping("/getUserTemplate")
    public void getUserTemplate(HttpServletRequest request,HttpServletResponse response){
        excelUtil.cooperation(request,response,User.class,"上传用户模板");
    }

    /**
     * 上传接口
     */
    @PostMapping("/importUser")
    @ResponseBody
    public ServerResponse<Object> importUsers(MultipartFile file){
        List<Object> upload = excelUtil.upload(file,User.class);
        return userService.importUsers(upload);
    }

}
